package cn.stylefeng.guns.modular.stock.controller;

import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.stock.model.StockInfo;
import cn.stylefeng.guns.unitl.SinaStockUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author eric xu
 * @date 2021/1/21
 * @description
 */
@ServerEndpoint("/webSocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    private static AtomicInteger onlineNum = new AtomicInteger();

    private static ConcurrentHashMap<String, ScheduledExecutorService> executors = new ConcurrentHashMap<>();


    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    public WebSocketServer() {
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String stockCode) {
        sessionPools.put(stockCode, session);
        addOnlineCount();
        System.out.println(stockCode + "加入webSocket！当前人数为" + onlineNum);
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        executors.put(stockCode, scheduledExecutorService);
        scheduledExecutorService
                .scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        StockInfo stockInfo = SinaStockUtil.getStockCodeData(stockCode);
                        try {
                            sendMessage(session, JSONUtil.toJsonStr(stockInfo));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, 1, 3, TimeUnit.SECONDS);


    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        ScheduledExecutorService scheduledExecutorService = executors.get(userName);
        if (!Objects.isNull(scheduledExecutorService)) {
            scheduledExecutorService.shutdown();
            executors.remove(userName);
        }
        log.info(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException {
        message = "客户端：" + message + ",已收到";
        System.out.println(message);
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}
